package com.hooper.util;

import com.hooper.model.dto.SysMenuDto;
import com.hooper.model.vo.MetaVo;
import com.hooper.model.vo.RouterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.hooper.constant.SysMenuConstant.*;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/04/02/14:08
 */
public class MenuHelper {

    public static List<SysMenuDto> toTree(List<SysMenuDto> menuDtoList) {
        List<SysMenuDto> topMenus = new ArrayList<>();
        for (SysMenuDto menu : menuDtoList) {
            if (menu.getParentId().equals(TOP_MENU_ID)) {
                topMenus.add(menu);
            }
            for (SysMenuDto subMenu : menuDtoList) {
                if (subMenu.getParentId().equals(menu.getId())) {
                    if (menu.getChildren() == null) {
                        menu.setChildren(new ArrayList<>());
                    }
                    menu.getChildren().add(subMenu);
                }
            }
        }
        return topMenus;
    }

    public static List<RouterVo> toRouter(List<SysMenuDto> menuDtoList) {
        List<RouterVo> routerList = new ArrayList<>();
        for (SysMenuDto menu : menuDtoList) {
            RouterVo router = new RouterVo();
            router.setPath(getPath(menu));
            router.setHidden(false);
            router.setAlwaysShow(false);
            router.setComponent(menu.getComponent());
            router.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
            List<SysMenuDto> children = menu.getChildren();
            if (menu.getType().equals(MENU_TYPE_TOP_MENU)) {
                List<SysMenuDto> subMenus = children.stream()
                        .filter(m -> StringUtils.isNotBlank(m.getComponent()))
                        .collect(Collectors.toList());
                for (SysMenuDto subMenu : subMenus) {
                    RouterVo hiddenRouter = new RouterVo();
                    hiddenRouter.setHidden(true);
                    hiddenRouter.setAlwaysShow(false);
                    hiddenRouter.setPath(getPath(subMenu));
                    hiddenRouter.setComponent(subMenu.getComponent());
                    hiddenRouter.setMeta(new MetaVo(subMenu.getName(), subMenu.getIcon()));
                    routerList.add(hiddenRouter);
                }
            } else {
                if (!CollectionUtils.isEmpty(children)) {
                    router.setAlwaysShow(true);
                    router.setChildren(toRouter(children));
                }
            }
            routerList.add(router);
        }
        return routerList;
    }

    private static String getPath(SysMenuDto menuDto) {
        String path = menuDto.getPath();
        return Objects.equals(menuDto.getParentId(), TOP_MENU_ID) ?
                '/' + path : path;
    }
}
